//
//  ZDBExtensionViewController.m
//  ZDB
//
//  Created by Kk on 2020/3/20.
//  Copyright © 2020 ZDB. All rights reserved.
//

#import "ZDBExtensionViewController.h"
#import "ZDBExtensionHeadView.h"
#import "ZDBRegisterInfoListModel.h"
@interface ZDBExtensionViewController ()
@property (nonatomic,strong)UIScrollView * scrollerView;
@property (nonatomic, strong) ZDBExtensionHeadView * tableviewHeadView;//数据
@property (nonatomic, strong) ZDBExtensionHeadView * tableviewHeadView1;//数据
@property (nonatomic, strong) ZDBExtensionHeadView * tableviewHeadView2;//数据
@property (nonatomic, strong) ZDBExtensionHeadView * tableviewHeadView3;//数据
@property (nonatomic, strong) ZDBExtensionHeadView * tableviewHeadView4;//数据
@property (nonatomic, strong) NSString * registerUrl;//邀请注册二维码
@property (nonatomic, strong) NSString * subitId;//提交任务ID
@property (nonatomic,assign)BOOL isReceive;//是否领取任务
@end

@implementation ZDBExtensionViewController
- (void)viewWillAppear:(BOOL)animated
{
     [self statusBarStyleIsDark:NO];
     [self SetnavigationBarBackgroundImage:RGBA(255, 79, 42, 1) Alpha:1];
     [self SetNavigationBarTitleColor:[UIColor whiteColor]];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [self statusBarStyleIsDark:YES];
    [self SetNavigationBarTitleColor:MAINTITLECOLOR];
    [self SetnavigationBarBackgroundImage:WHITECOLOR Alpha:1];
    [super viewWillDisappear:animated];
}
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
//    self.tableviewHeadView.frame = CGRectMake(0, 0, UIScreenWidth, 280);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"推广任务详情";
    [self initBackButton:YES];
    [self.view addSubview:self.scrollerView];
    [self initCustom];
    _tableviewHeadView = [[NSBundle mainBundle] loadNibNamed:@"ZDBExtensionHeadView" owner:self options:nil][0];
    _tableviewHeadView.frame = CGRectMake(0, 214, RealValue_W(345*2), RealValue_W(260));
    WeakSelf
    KViewRadius(_tableviewHeadView, 4);
    [_tableviewHeadView.receiveBtn add_BtnClickHandler:^(NSInteger tag) {//领取任务
        [weakSelf buttonClick:1];
    }];
    _tableviewHeadView.centerX =self.scrollerView.centerX;
    [self.scrollerView addSubview:self.tableviewHeadView];
    
    
    _tableviewHeadView1 = [[NSBundle mainBundle] loadNibNamed:@"ZDBExtensionHeadView" owner:self options:nil][1];
    _tableviewHeadView1.frame = CGRectMake(0, 214, RealValue_W(345*2), 205);
    KViewRadius(_tableviewHeadView1, 4);
    [_tableviewHeadView1.invitationBtn add_BtnClickHandler:^(NSInteger tag) {//邀请二维码
        
         [weakSelf buttonClick:3];
    }];
    [_tableviewHeadView1.urlCopyBtn add_BtnClickHandler:^(NSInteger tag) {//复制链接
        
         [weakSelf buttonClick:4];
    }];
    
    _tableviewHeadView1.centerX =self.scrollerView.centerX;
    [self.scrollerView addSubview:self.tableviewHeadView1];
    
    _tableviewHeadView2 = [[NSBundle mainBundle] loadNibNamed:@"ZDBExtensionHeadView" owner:self options:nil][2];
    _tableviewHeadView2.frame = CGRectMake(0, 214, RealValue_W(345*2), 205);
    KViewRadius(_tableviewHeadView2, 4);
    [_tableviewHeadView2.subomtBtn add_BtnClickHandler:^(NSInteger tag) {//提交任务
        [weakSelf buttonClick:2];
    }];
    _tableviewHeadView2.centerX =self.scrollerView.centerX;
    [self.scrollerView addSubview:self.tableviewHeadView2];
    
    _tableviewHeadView3 = [[NSBundle mainBundle] loadNibNamed:@"ZDBExtensionHeadView" owner:self options:nil][3];
    _tableviewHeadView3.frame = CGRectMake(0, 214, RealValue_W(345*2), 250);
    KViewRadius(_tableviewHeadView3, 4);
    _tableviewHeadView3.centerX =self.scrollerView.centerX;
    [self.scrollerView addSubview:self.tableviewHeadView3];
  
    _tableviewHeadView4 = [[NSBundle mainBundle] loadNibNamed:@"ZDBExtensionHeadView" owner:self options:nil][4];
    _tableviewHeadView4.frame = CGRectMake(0, 214, RealValue_W(345*2), 200);
    KViewRadius(_tableviewHeadView4, 4);
    _tableviewHeadView4.centerX =self.scrollerView.centerX;
    [self.scrollerView addSubview:self.tableviewHeadView4];
    [self getRegisterTaskById];//获取二级任务详情
}
- (void)initCustom
{
    UILabel * lable = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, UIScreenWidth-20, 36)];
    lable.textColor = WHITECOLOR;
    lable.font = AutoBoldFont(30);
    lable.text  = @"邀好友赢大奖";
    lable.textAlignment = NSTextAlignmentCenter;
    [_scrollerView addSubview:lable];
    
    UILabel * profitLable = [[UILabel alloc] initWithFrame:CGRectMake(10, lable.bottom +10, UIScreenWidth-20, 21)];
    profitLable.textColor = ColorStr(@"FBF14A");
    profitLable.font = AutoBoldFont(21);
    profitLable.text  = @"获得红包和积分奖励";
    profitLable.textAlignment = NSTextAlignmentCenter;
    [_scrollerView addSubview:profitLable];
    
    UIImageView * headImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, profitLable.bottom+10, 254, 192)];
    headImg.image = [UIImage imageNamed:@"extension_bg"];
    headImg.centerX = profitLable.centerX;
    [_scrollerView addSubview:headImg];
}
#pragma 获取二级任务详情
- (void)getRegisterTaskById
{
    [self showLoadingAnimation];
    WeakSelf
    NSString  * getRegisterTaskById = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getRegisterTaskById"];
    [[SmileHttpTool sharedInstance] POST:getRegisterTaskById parameters:@{@"id":_id} origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
        
        if (statusCode==0) {
            if (kObjectIsEmpty(responseObject[@"taskRegister"])) {
                [JMNotifyView showNotify:@"获取任务详情失败" isSuccessful:NO];;
                return ;
            }
            NSDictionary * taskRegister = responseObject[@"taskRegister"];//注册信息
            NSDictionary * taskUserRegister = responseObject[@"taskUserRegister"];//邀请信息
            
            NSArray * taskUserRegisterInfoList = taskRegister[@"taskUserRegisterInfoList"];
            NSArray * registerList  = [ZDBRegisterInfoListModel mj_objectArrayWithKeyValuesArray:taskUserRegisterInfoList];
            [weakSelf.tableviewHeadView3 getUserRegisterList:registerList];
            NSString * taskUrl = taskRegister[@"taskUrl"];
            [weakSelf.tableviewHeadView.icon sd_setImageWithURL:[NSURL URLWithString:taskUrl] placeholderImage:[UIImage imageNamed:@"Extension_Invitation"]];
             [weakSelf.tableviewHeadView2.icon sd_setImageWithURL:[NSURL URLWithString:taskUrl] placeholderImage:[UIImage imageNamed:@"Extension_Invitation"]];
             [weakSelf.tableviewHeadView3.icon sd_setImageWithURL:[NSURL URLWithString:taskUrl] placeholderImage:[UIImage imageNamed:@"Extension_Invitation"]];
            
            if (kDictIsEmpty(taskUserRegister)) { //为空表示可领取任务 否是已经领取任务展示邀请信息
                weakSelf.isReceive = NO;
                 [weakSelf getTaskRegisterInfo:taskRegister];

            }else
            {
                weakSelf.subitId = kFormat(@"%@", taskUserRegister[@"id"]);
                weakSelf.isReceive = YES;
                [weakSelf getTaskUserRegister:taskUserRegister];
            }
        }else
        {
            [JMNotifyView showNotify:message isSuccessful:NO];
            
        }
        [weakSelf stopLoadingAnimation];
        
    } failure:^(id responseObject, NSError *error) {
        [weakSelf stopLoadingAnimation];
        
    }];
}
#pragma 获取注册信息
- (void)getTaskRegisterInfo:(NSDictionary *)dic
{
    self.extensionType = ExtensionReceiveType;
    [self getExtentWith:self.extensionType];
    _scrollerView.hidden = NO;
    NSString * num = kFormat(@"邀请好友注册（%@人）", dic[@"askNumber"]);
    _tableviewHeadView.invitationNum.attributedText = [ZBDUnit finderattributedString:num attributedString:kFormat(@"%@", dic[@"askNumber"]) color:MAINCOLOR font: AutoBoldFont(18)];
    
     NSString * integranum = kFormat(@"可获得 %@元  %@积分", dic[@"money"],dic[@"integral"]);
    
    _tableviewHeadView.integralNum.attributedText = [ZBDUnit finderattributedString:integranum attributedArray:@[kFormat(@"%@", dic[@"money"]),kFormat(@"%@", dic[@"integral"])] colors:@[MAINCOLOR,MAINCOLOR] font:AutoFont(16)];
    
}
#pragma 获取邀请信息
- (void)getTaskUserRegister:(NSDictionary *)dic
{
    _scrollerView.hidden = NO;
    NSString * num = kFormat(@"邀请好友注册（%@人）", dic[@"askNumber"]);
    
    _tableviewHeadView1.InvitationNum1.attributedText = _tableviewHeadView2.InvitationNum2.attributedText = [ZBDUnit finderattributedString:num attributedString:kFormat(@"%@", dic[@"askNumber"]) color:MAINCOLOR font: AutoBoldFont(18)];
    
     NSString * integranum = kFormat(@"可获得 %@元  %@积分", dic[@"money"],dic[@"integral"]);
    _tableviewHeadView1.integralNum1.attributedText = _tableviewHeadView2.integralNum2.attributedText = [ZBDUnit finderattributedString:integranum attributedArray:@[kFormat(@"%@", dic[@"money"]),kFormat(@"%@", dic[@"integral"])] colors:@[MAINCOLOR,MAINCOLOR] font:AutoFont(16)];
    NSInteger askNumber = [dic[@"askNumber"] integerValue];//需要人数
    NSInteger completeNumber = [dic[@"completeNumber"] integerValue];//已邀请人数
    _registerUrl = dic[@"registerUrl"];//邀请注册地址
     NSString * state = dic[@"state"];
    if (completeNumber>=askNumber) {//大于或者等于的时候可以提交任务
        
         self.extensionType = ExtensionOKType;
        [self getExtentWith:self.extensionType];
        switch (state.integerValue) {//1=进行中 2=审核中 3=已完成
            case 1:
               _tableviewHeadView2.subomtBtn.userInteractionEnabled = YES;
                [_tableviewHeadView2.subomtBtn setTitle:@"可提交" forState:0];
                _tableviewHeadView2.subomtBtn.alpha =1;
                break;
            case 2:
                _tableviewHeadView2.subomtBtn.userInteractionEnabled = NO;
                [_tableviewHeadView2.subomtBtn setTitle:@"审核中" forState:0];
                _tableviewHeadView2.subomtBtn.alpha =0.5;
                break;
            case 3:
                _tableviewHeadView2.subomtBtn.userInteractionEnabled = YES;
                [_tableviewHeadView2.subomtBtn setTitle:@"已完成" forState:0];
                _tableviewHeadView2.subomtBtn.alpha =1;
                break;
            default:
                break;
        }
        
    }else
    {
        self.extensionType = ExtensionHaveInHandType;
        [self getExtentWith:self.extensionType];
        if (state.integerValue ==1) {
            _tableviewHeadView2.subomtBtn.userInteractionEnabled = NO;
            [_tableviewHeadView2.subomtBtn setTitle:@"进行中" forState:0];
           
        }
       
    }
     
    NSString * already_invited_num = kFormat(@"已邀请 %@ 人  还剩 %@ 人", @(completeNumber),@(askNumber - completeNumber));
    _tableviewHeadView1.already_invited_num.attributedText = [ZBDUnit finderattributedString:already_invited_num attributedArray:@[kFormat(@"%@", @(completeNumber)),kFormat(@"%@", @(askNumber - completeNumber)) ] colors:@[MAINCOLOR,MAINCOLOR] font:AutoBoldFont(18)];
    
    _tableviewHeadView1.already_invited_num.textAlignment =  NSTextAlignmentCenter;
     NSString * already_invited_num2 = kFormat(@"恭喜您，邀请任务已达标，提交任务后\n即可获得%@元  %@积分奖励",dic[@"money"],dic[@"integral"]);
    
    _tableviewHeadView2.already_invited_num2.attributedText = [ZBDUnit finderattributedString:already_invited_num2 attributedArray:@[kFormat(@"%@", dic[@"money"]),kFormat(@"%@", dic[@"integral"])] colors:@[MAINCOLOR,MAINCOLOR] font:AutoFont(15)];
     _tableviewHeadView2.already_invited_num2.textAlignment =  NSTextAlignmentCenter;
}
//type =1 领取任务
- (void)buttonClick:(NSInteger)type
{
    if (![ZBDUnit getLoginJurisdiction]) {
        return;
    }
    switch (type) {
        case 1://领取任务
            {
             
                [self userReceiveRegisterTask];
            }
            break;
        case 2://提交任务
        {
            [self submitTaskRegisterTask];
        }
            break;
        case 3://邀请二维码
        {
            if (!_isReceive) {
                [JMNotifyView showNotify:@"请先领取任务" isSuccessful:NO];
            }else
            {
                NSDictionary * dic = @{@"shareUrl":_registerUrl};
                [[ZDBAlertHelper sharedInstance] alert_PopEShareWith:dic isNmuberShoare:NO isInvitationShoare:YES andActionBlock:^(NSInteger actionType) {
                    
                }];
            }
           
        }
            break;
        case 4://复制链接
        {
            if (!_isReceive) {
                 [JMNotifyView showNotify:@"请先领取任务" isSuccessful:NO];
            }else
            {
                UIPasteboard * pastboard = [UIPasteboard generalPasteboard];
                pastboard.string = _registerUrl;
                [JMNotifyView showNotify:@"邀请链接已复制到粘贴板" isSuccessful:YES];
            }
           
        }
            break;
            
            
        default:
            break;
    }
    
}
#pragma 领取二级任务
- (void)userReceiveRegisterTask
{
    [self showLoadingAnimation];
    WeakSelf
    NSString  * userReceiveRegisterTask = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"userReceiveRegisterTask"];
    [[SmileHttpTool sharedInstance] POST:userReceiveRegisterTask parameters:@{@"id":_id} origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
        
        if (statusCode==0) {
            
             NSDictionary * taskUserRegister = responseObject[@"taskUserRegister"];//邀请信息
            if (!kDictIsEmpty(taskUserRegister)) {
                weakSelf.isReceive = YES;
                [weakSelf getTaskUserRegister:taskUserRegister];
                
             }
            if (self.taskSuccess) {
                self.taskSuccess();
            }
            
        }else
        {
            [JMNotifyView showNotify:message isSuccessful:NO];
        }
        [weakSelf stopLoadingAnimation];
        
    } failure:^(id responseObject, NSError *error) {
        [weakSelf stopLoadingAnimation];
        
    }];
   
}
#pragma 提交二级任务
- (void)submitTaskRegisterTask
{
    [self showLoadingAnimation];
       WeakSelf
       NSString  * submitTaskRegisterTask = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"submitTaskRegisterTask"];
       [[SmileHttpTool sharedInstance] POST:submitTaskRegisterTask parameters:@{@"id":weakSelf.subitId} origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
           
           if (statusCode==0) {
                [JMNotifyView showNotify:@"任务已提交" isSuccessful:NO];
               if (self.taskSuccess) {
                   self.taskSuccess();
               }
               [weakSelf.navigationController popViewControllerAnimated:YES];
               
               
           }else
           {
               [JMNotifyView showNotify:message isSuccessful:NO];
           }
           [weakSelf stopLoadingAnimation];
           
       } failure:^(id responseObject, NSError *error) {
           [weakSelf stopLoadingAnimation];
           
       }];
}
- (void)getExtentWith:(ExtensionType)extensionType
{
    
    switch (extensionType) {
        case ExtensionReceiveType:
        {
            _tableviewHeadView.hidden = _tableviewHeadView4.hidden = NO;
            _tableviewHeadView1.hidden =  _tableviewHeadView2.hidden = _tableviewHeadView3.hidden = YES;
            _tableviewHeadView.frame = CGRectMake(0, 214, RealValue_W(345*2), RealValue_W(260));
            _tableviewHeadView4.frame =  CGRectMake(0, _tableviewHeadView.bottom +20, RealValue_W(345*2), 200);
            _tableviewHeadView.centerX =  _tableviewHeadView4.centerX = self.scrollerView.centerX;
        }
            
            break;
        case ExtensionHaveInHandType:
        {
            _tableviewHeadView1.hidden =  _tableviewHeadView3.hidden = _tableviewHeadView4.hidden = NO;
            _tableviewHeadView.hidden = _tableviewHeadView2.hidden = YES;
            _tableviewHeadView1.frame = CGRectMake(0, 214, RealValue_W(345*2), 205);
           
            _tableviewHeadView3.frame =  CGRectMake(0, _tableviewHeadView1.bottom +20, RealValue_W(345*2), 250);
            _tableviewHeadView4.frame =  CGRectMake(0, _tableviewHeadView3.bottom +20, RealValue_W(345*2), 200);
            _tableviewHeadView1.centerX =  _tableviewHeadView3.centerX = _tableviewHeadView4.centerX = self.scrollerView.centerX;
            [_scrollerView setContentSize:CGSizeMake(UIScreenWidth, _tableviewHeadView1.height + _tableviewHeadView3.height+ _tableviewHeadView4.height +214 +100)];
        }
            
            break;
        case ExtensionOKType:
        {
             _tableviewHeadView2.hidden = _tableviewHeadView3.hidden = _tableviewHeadView4.hidden = NO;
            _tableviewHeadView.hidden = _tableviewHeadView1.hidden = YES;
            _tableviewHeadView2.frame = CGRectMake(0, 214, RealValue_W(345*2), 205);
            _tableviewHeadView3.frame =  CGRectMake(0, _tableviewHeadView2.bottom +20, RealValue_W(345*2), 250);
            _tableviewHeadView4.frame =  CGRectMake(0, _tableviewHeadView3.bottom +20, RealValue_W(345*2), 200);
            _tableviewHeadView2.centerX = _tableviewHeadView3.centerX = _tableviewHeadView4.centerX = self.scrollerView.centerX;
            
             [_scrollerView setContentSize:CGSizeMake(UIScreenWidth, _tableviewHeadView2.height + _tableviewHeadView3.height+ _tableviewHeadView4.height +214 +100)];
        }
            
            break;
            
        default:
            break;
    }
}
- (UIScrollView *)scrollerView
{
    if (!_scrollerView) {
        _scrollerView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight -kStatusBarAndNavigationBarHeight)];
        _scrollerView.backgroundColor = CLEARCOLOR;
        _scrollerView.showsVerticalScrollIndicator = NO;
        _scrollerView.showsHorizontalScrollIndicator = NO;
        _scrollerView.hidden = YES;
    }
    return _scrollerView;
}

@end
